import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import bcrypt from "bcrypt";
import { Student } from "@db";
import { config } from "@config";

//Подробнее о возможностях валидации лучше смотреть тут - https://github.com/sinclairzx81/typebox
const signInBody = Type.Object({
    email: Type.String({ format: "email" }),
    password: Type.String({ minLength: 6, maxLength: 512 }),
});

export const signIn = async (fastify: FastifyInstance) => {
    fastify.post<{ Body: Static<typeof signInBody> }>(
        "/student/signIn",
        {
            schema: {
                tags: ["student"],
                body: signInBody,
            },
        },
        async (req, res) => {
            const { email, password } = req.body;

            const student = await Student.findOne({
                where: {
                    email,
                },
            });
            //TODO: REWRITEEE
            if (!student)
                return res.status(401).send({
                    code: "USER_NOT_EXISTS",
                    message: "Введённые вами почта или пароль неверны",
                });
            const match = await bcrypt.compare(password, student?.password);
            if (!match)
                return res.status(401).send({
                    code: "USER_NOT_EXISTS",
                    message: "Введённые вами почта или пароль неверны",
                });

            req.session.student = {
                id: student.id,
            };
            if (!student.isVerified)
                return res.status(409).send({
                    code: "USER_NOT_VERIFED",
                    message: "Вы не верифицировали аккаунт",
                });

            return res.send({
                ...student.dataValues,
                photo: student.photo
                    ? "https://" +
                      config.host +
                      "/files/avatars/" +
                      student.photo
                    : null,
                password: undefined,
                updatedAt: undefined,
            });
        }
    );
};
